﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Threading;
using System.Diagnostics;
using INdTFramework.Maps;

namespace ToastNotificationSample
{
    public partial class SecondPage : PhoneApplicationPage
    {
        // Timer.
        DispatcherTimer timer;

        public SecondPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            // Instantiation of the timer.
            // It's created to check whether object 'App.Geolocation' already obtained valid coordinates of the user.
            // In addition, every 5 seconds one toast notification will be displayed if the application is running in background.
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            if (App.Geolocation.IsFinished)
            {
                if (App.Geolocation.Status != System.Device.Location.GeoPositionStatus.Disabled &&
                    App.Geolocation.Status != System.Device.Location.GeoPositionStatus.NoData)
                {
                    // If the coordinates of the user were obtained successfully, the latitude is displayed to the user.
                    Longitude.Text = App.Geolocation.Longitude.ToString();
                }
            }

            // If the application is running in background and the last page before going to the background was the SecondPage.xaml page, the toast notification is displayed to the user.
            if (App.IsRunningInBackground && (Application.Current.RootVisual as PhoneApplicationFrame).CurrentSource.ToString() == "/SecondPage.xaml")
            {
                // Function to display the toast notification.
                ShowToast();
            }
        }

        void ShowToast()
        {
            // Instantiation of a toast notification.
            // The toast notification will not be displayed if the application is running in foreground.
            var toast = new ShellToast();

            // Definition of the toast title.
            toast.Title = "INdT FRAMEWORK";

            // Definition of the toast message.
            toast.Content = "See current latitude.";

            // Command that displays the toast notification to the user.
            // As it was not defined the URI to navigate then the default URI is the URI of the navigation page of the application.
            toast.Show();
        }
    }
}